package com.kancy.drools.tools;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * <p>
 * Log
 * <p>
 *
 * @author: kancy
 * @date: 2020/3/15 13:18
 **/

public class Log {

    private Log() {
        throw new UnsupportedOperationException("工具类不支持实例化");
    }

    private static DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss,SSS");

    public static void info(String msgFormat, Object ... args){
        log(msgFormat, args, false);
    }

    public static void error(String msgFormat, Object ... args){
        log(msgFormat, args, true);
    }

    /**
     * 打印日志
     * @param msgFormat
     * @param args
     */
    private static void log(String msgFormat, Object[] args, boolean isError) {
        if (Objects.nonNull(msgFormat)) {
            msgFormat = msgFormat.replace("{}", "%s");

            StringBuffer log = new StringBuffer();
            log.append(LocalDateTime.now().format(DATETIME_FORMATTER));
            log.append(" [").append(getThreadName()).append("] : ");
            log.append(String.format(msgFormat, args));

            if (isError){
                System.err.println(log.toString());
            }else {
                System.out.println(log.toString());
            }
        }
    }

    /**
     * ThreadName
     * @return
     */
    private static String getThreadName() {
        String tmp = Thread.currentThread().getName();
        if (tmp.length() > 10){
            tmp = tmp.substring(tmp.length() -10);
        }
        return String.format("%-10s", tmp);
    }
}
